<%@ taglib prefix="s" uri="/struts-tags" %>
$(document).ready(function () {

	var minLevel = <s:property value="minLevel" />;
	var maxLevel = <s:property value="maxLevel" />;
	
	$(".levelValue").each(function() {
		var levelValue = $(this).val() || 12127;
		
		if (levelValue == minLevel ||
			levelValue == maxLevel) {
			$(this).attr('readonly', 'readonly');
			$(this).addClass('readOnly');
			
		}
		
	});

	/*
	 * Only perform this function on ready, requires input
	 * fields to have values.
	 */
	var insertFlag = false;
	var deleteFlag = false;
	$(".levelItem").each(function() {
		var levelValue = $(".levelValue", this).val() || 12127;
		if (levelValue != maxLevel) {
			insertFlag = true;
				
		}
		
		
		if ((levelValue > minLevel && levelValue < maxLevel) || levelValue == 12127) {
			deleteFlag = true;
			
		}
		addLevelDecorators(this, insertFlag, deleteFlag);
		insertFlag = deleteFlag = false;
		
	});
	
});

var levelInput = '<li class="levelItem"><input type="hidden" name="levelId" value="-1" /><input type="text" name="levelValue" size="5" maxlength="4" value="" class="levelValue" /><input type="text" name="levelName" size="25" maxlength="20" value="" class="levelName" /> </li>';

function addLevelDecorators(element, isInsert, isDelete) {

	if (isInsert) {
		$('<a href="#" class="insertLevel">Insert Level</a>').appendTo(element);
		$("a.insertLevel", element).click(function() {
			$(element).after(levelInput);
			addLevelDecorators($(element).next(), true, true);
			return false;
			
		});
		
	}

	if (isDelete) {
		$("<span>, </span>").appendTo(element);
		$('<a href="#" class="deleteLevel">Delete Level</a>').appendTo(element);
		$("a.deleteLevel", element).click(function() {
			var companyId;
			var levelId;
			var level;
			if (!(companyId = $("#company_id").val())) {

			} else if (!(levelId = $(".levelId", element).val())) {
				
			} else if (!(level = getLevel(companyId, levelId))) {

			} else {
				if (level.itemCount > 0) {
					alert("Level cannot be deleted, hierarchy items are still assigned.");
					return false;
				}
				
			} 
			$(element).remove();
			return false;
			
		});
		
	}
	
}

